package netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;


/**
 * Created with IntelliJ IDEA.
 * User: SuQiEr
 * Date:2017/5/13 0013
 * Time: 下午 10:23
 * To change this template use File | Settings | File Templates.
 */
public class ServiceHandler extends ChannelInboundHandlerAdapter {


    @Override
    public  void channelRead(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {


        System.out.println("接收到客户端请求:"+o.getClass());



        if(o instanceof  HttpRequest){
            HttpRequest request = (HttpRequest)o;
            URI uri = new URI(request.getUri());
            System.out.println("请求路径:"+uri.getPath());
        //服务端处理接受和发送消息
        ByteBuf byteBuf = Unpooled.copiedBuffer("Hello World", CharsetUtil.UTF_8);

        FullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                HttpResponseStatus.OK,byteBuf);
       defaultFullHttpResponse.headers().set("Content-Type","text/plain");
        defaultFullHttpResponse.headers().set("Content-Length",byteBuf.readableBytes());
            //ByteBuf in = (ByteBuf)o;
            //System.out.println("server received :" +in.toString(CharsetUtil.UTF_8));
            channelHandlerContext.writeAndFlush(defaultFullHttpResponse);
        }
    }
}
